<template>
  <div class="chat-container">
    <!-- 消息展示区域 -->
    <div class="messages" ref="messagesContainer">
      <div 
        v-for="(msg, index) in messages"
        :key="index"
        :class="['message', { 'ai': msg.role === 'assistant' }]"
      >
        <div class="bubble">
          {{ msg.content }}
          <div v-if="msg.loading" class="loading-indicator">...</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <input
        v-model="inputText"
        @keyup.enter="sendMessage"
        :disabled="isLoading"
        placeholder="输入消息..."
      />
      <button @click="sendMessage" :disabled="isLoading || !inputText.trim()">
        {{ isLoading ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, watch, onMounted } from 'vue';
import {useUserStore} from '../../store/modules/user';
import { useJournalStore} from '../../store/modules/journal'
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8080/api/ai/chat'
const TOKEN = useUserStore().token;
// 响应式数据
const messages = reactive([])
const inputText = ref('')
 let userMessage = ref("") 
const isLoading = ref(false)
const messagesContainer = ref(null)
let  systemMsg = ref("")
const JSstate = useJournalStore()

// 添加消息到列表
const addMessage = (content, role = 'user') => {
  messages.push({
    role,
    content,
    loading: role === 'assistant'
  })
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 处理流式响应
const processStream = async (reader) => {
  const decoder = new TextDecoder('utf-8')
  let buffer = ''
  
  try {
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      
      buffer += decoder.decode(value, { stream: true })
      
      // 处理完整消息块
      const chunks = buffer.split('\n')
      buffer = chunks.pop() || '' // 保留未完成部分
      
      chunks.forEach(chunk => {
        const lastMsg = messages[messages.length - 1]
        if (lastMsg && lastMsg.role === 'assistant') {
          lastMsg.content += chunk
          lastMsg.loading = false
        }
      })
      
      await scrollToBottom()
    }
    
    // 处理剩余buffer
    if (buffer) {
      const lastMsg = messages[messages.length - 1]
      if (lastMsg) {
        lastMsg.content += buffer
        lastMsg.loading = false
      }
    }
  } catch (error) {
    console.error('流处理错误:', error)
    addMessage('响应中断，请重试', 'assistant')
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || isLoading.value) return

  try {
    isLoading.value = true
     userMessage.value = inputText.value.trim()
    inputText.value = ''
    
    // 添加用户消息
    addMessage(userMessage.value, 'user')
    
    // 添加AI占位消息
    addMessage('', 'assistant')
    await scrollToBottom()

    // 发起请求
    const response = await fetch(`${API_URL}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${TOKEN}`,
        "Token":TOKEN
      },
      body: JSON.stringify ({
        prompt: userMessage.value,
        system: systemMsg.value
      })
    })

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`)
    }

    if (!response.body) {
      throw new Error('未接收到有效响应流')
    }

    // 处理流式响应
    await processStream(response.body.getReader())
    
  } catch (error) {
    console.error('请求错误:', error)
    addMessage(`服务器繁忙`, 'assistant')
  } finally {
    isLoading.value = false
    await scrollToBottom()
  }
}

onMounted ( async () => { 

if(JSstate.aibutton){
  console.log('aibutton',JSstate.aibutton)
  inputText.value = "已发送相关信息";
  systemMsg.value = JSstate.systemMsg
  await sendMessage();
  JSstate.aibutton = false;
}
})


</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 15px;
}

.message {
  margin-bottom: 15px;
  display: flex;
}

.message.ai {
  justify-content: flex-start;
}

.message:not(.ai) {
  justify-content: flex-end;
}

.bubble {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 15px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: relative;
}

.message.ai .bubble {
  background: #e3f2fd;
}

.loading-indicator {
  color: #666;
  font-size: 24px;
}

.input-area {
  display: flex;
  gap: 10px;
}

input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
}

button {
  padding: 12px 24px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.2s;
}

button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background: #0056b3;
}
</style>